package com.taobao.askwho.ao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.log4j.Logger;

import com.taobao.askwho.db.impl.CombineDao;
import com.taobao.askwho.po.PersonInfo;
import com.taobao.askwho.po.TagRelation;
import com.taobao.askwho.po.UrlInfo;
import com.taobao.askwho.utils.ToolUtil;
import com.taobao.askwho.vo.PersonalPageRecordVo;

/**
 * 组合其他AO的复杂操作 
 * @author zhongting.zy
 */
public class ComplexAo {
	public static final Logger logger = Logger.getLogger(ComplexAo.class);
	private ComplexAo(){};
	private static ComplexAo complexAo = new ComplexAo();
	private static CombineDao combineDao = new CombineDao();
	public static ComplexAo get() {
		return complexAo;
	}
	
	public void addNewUrl(String urlContent, boolean isPublic, String[] tagNameArray, String userUuid) throws Exception {
		final String urlUuid = UUID.randomUUID().toString();  
		final Date createDate = new Date();
		UrlInfo urlInfo = new UrlInfo();
		urlInfo.setUuid(urlUuid);
		urlInfo.setUrlContent(urlContent);
		urlInfo.setCreateTime(createDate);
		urlInfo.setUpdateTime(createDate);
		UrlAo.get().addUrlInfo(urlInfo);//出现异常直接抛给上级
		
		final Set<String> tagUuidSet = new HashSet<String>();
		try {
			for(String tagName : tagNameArray) {
				TagRelation tagRelation = new TagRelation();
				String uuid = UUID.randomUUID().toString();
				tagUuidSet.add(uuid);
				tagRelation.setUuid(uuid);
				tagRelation.setTagName(tagName);
				tagRelation.setType("url");
				tagRelation.setPublic(isPublic);
				tagRelation.setUserUuid(userUuid);
				tagRelation.setRelatedUuid(urlUuid);
				tagRelation.setCreateTime(createDate);
				tagRelation.setUpdateTime(createDate);
				TagAo.get().addTagRelation(tagRelation);
			}
		} catch (Exception e) {
			logger.error("", e);
			try {
				logger.error("出现异常，删除刚刚添加的Tag->" + tagUuidSet);
				TagAo.get().deleteTagRelationByUuid(tagUuidSet);
			} catch (Exception e2) {
				logger.error("", e2);
			}
			
			try {
				logger.error("出现异常，删除刚刚添加的url->" + urlUuid);
				UrlAo.get().deleteUrlInfo(urlUuid);
			} catch (Exception e2) {
				logger.error("", e2);
			}
			throw e;
		}
	}
	
	public void addNewPerson(String personName, boolean isPublic, String wangwang, String[] tagNameArray, String userUuid) throws Exception {
		final String personUuid = UUID.randomUUID().toString();  
		final Date createDate = new Date();
		PersonInfo info = new PersonInfo();
		info.setUuid(personUuid);
		info.setPersonName(personName);
		info.setWangwang(wangwang);
		info.setCreateTime(createDate);
		info.setUpdateTime(createDate);
		info.setMd5(ToolUtil.getMD5String(personName + "_" + wangwang));
		PersonAo.get().addPersonInfo(info);//出现异常直接抛给上级
		
		final Set<String> tagUuidSet = new HashSet<String>();
		try {
			for(String tagName : tagNameArray) {
				TagRelation tagRelation = new TagRelation();
				String uuid = UUID.randomUUID().toString();
				tagUuidSet.add(uuid);
				tagRelation.setUuid(uuid);
				tagRelation.setTagName(tagName);
				tagRelation.setType("person");
				tagRelation.setPublic(isPublic);
				tagRelation.setUserUuid(userUuid);
				tagRelation.setRelatedUuid(personUuid);
				tagRelation.setCreateTime(createDate);
				tagRelation.setUpdateTime(createDate);
				TagAo.get().addTagRelation(tagRelation);
			}
		} catch (Exception e) {
			logger.error("", e);
			try {
				logger.error("出现异常，删除刚刚添加的Tag->" + tagUuidSet);
				TagAo.get().deleteTagRelationByUuid(tagUuidSet);
			} catch (Exception e2) {
				logger.error("", e2);
			}
			
			try {
				logger.error("出现异常，删除刚刚添加的person->" + personUuid);
				PersonAo.get().deletePersonInfo(personUuid);
			} catch (Exception e2) {
				logger.error("", e2);
			}
			throw e;
		}
	}	
	
	/**
	 *	根据uuid获取自己收藏的url和person 
	 */
	public List<PersonalPageRecordVo> getPersonalInfoAll(String userUuid) {
		try {
			Map<String, PersonalPageRecordVo> urlMap = combineDao.findUrlTagRecordByUserUuid(userUuid);
			Map<String, PersonalPageRecordVo> peopleMap = combineDao.findPeopleTagRecordByUserUuid(userUuid);
			List<PersonalPageRecordVo> list = new ArrayList<PersonalPageRecordVo>(urlMap.values());
			list.addAll(peopleMap.values());
			Collections.sort(list, new Comparator<PersonalPageRecordVo>() {
				@Override
				public int compare(PersonalPageRecordVo o1,
						PersonalPageRecordVo o2) {
					//时间降序
					return o2.getUpdateTimeStr().compareTo(o1.getUpdateTimeStr());
				}
			});
			return list;
		} catch (Exception e) {
			logger.error("", e);
		}
		return new ArrayList<PersonalPageRecordVo>();
	}
	
	//收藏某个用户的全部public标签
	public String collectOtherTags(String myUuid, String otherUuid) {
		StringBuilder sb = new StringBuilder();
		List<PersonalPageRecordVo> itemList = ComplexAo.get().getPersonalInfoAll(otherUuid);
		for(PersonalPageRecordVo vo : itemList) {
			if(!vo.isPublic())
				continue;
			try {
				if (vo.getType().equals("url")) {
					addNewUrl(vo.getUrlInfo().getUrlContent(), vo.isPublic(),
							vo.getTagNamesSet().toArray(new String[0]), myUuid);
				} else if (vo.getType().equals("person")) {
					addNewPerson(vo.getPersonInfo().getPersonName(),
							vo.isPublic(), vo.getPersonInfo().getWangwang(), vo
									.getTagNamesSet().toArray(new String[0]),
							myUuid);
				}
			} catch (Exception e) {
				sb.append(" 出现异常->" + e.toString());
			}
		}
		return sb.toString();
	}
	
	public List<PersonalPageRecordVo> findResultByUuids(List<String> uuidList) {
		List<PersonalPageRecordVo> listReturn = new ArrayList<PersonalPageRecordVo>();
		if(uuidList == null || uuidList.size() ==0)
			return listReturn;
		
		try {
			Map<String, PersonalPageRecordVo> map = combineDao.findResultByUuids(uuidList);
			for(String uuid:uuidList) {
				PersonalPageRecordVo vo = map.get(uuid);
				if(vo != null)
					listReturn.add(vo);
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return listReturn;
	}
	
	/**
	 * 丰富solr查询结果，不改变排序
	 * @param volist
	 * @return
	 */
	public List<PersonalPageRecordVo> findResultByVoList(List<PersonalPageRecordVo> volist) {
		if(volist == null || volist.size() ==0)
			return volist;

		List<String> personList = new ArrayList<String>();
		List<String> urlList = new ArrayList<String>();
		
		for(PersonalPageRecordVo rel : volist) {
			if(rel.getType().equals("person")) {
				personList.add(rel.getPersonInfo().getUuid());
			} else if(rel.getType().equals("url")) {
				urlList.add(rel.getUrlInfo().getUuid());
			} 
			continue;
		}
		Map<String, UrlInfo> urlMap = UrlAo.get().getUrlListByUuidList(urlList);
		Map<String, PersonInfo> personMap = PersonAo.get().getPersonListByUuidList(personList);
		Iterator<PersonalPageRecordVo> iter = volist.iterator();
		while(iter.hasNext()) {
			PersonalPageRecordVo rel = iter.next();
			if(rel.getType().equals("person")) {
				PersonInfo person = personMap.get(rel.getPersonInfo().getUuid());
				if(person == null)
					iter.remove();
				rel.setPersonInfo(person);
			} else if(rel.getType().equals("url")) {
				UrlInfo url = urlMap.get(rel.getUrlInfo().getUuid());
				if(url == null)
					iter.remove();				
				rel.setUrlInfo(url);
			} 
			continue;			
		}
		return volist;
	}	
}
